package com.project;

import com.project.comfig.MVCConfig;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;

public class MainMessage {
    public MainMessage(){
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8088);
        tomcat.getConnector();

        Context webContext = tomcat.addContext("",null);
        //产生前端控制器的对象
        DispatcherServlet dispatcher = new DispatcherServlet(
                this.getWebApplicationContext(webContext.getServletContext()));
        //注册前端控制器
        Wrapper w = Tomcat.addServlet(webContext,"springMVC",dispatcher);
        //容器启动完成初始化
        w.setLoadOnStartup(0);
        //配置访问路径
        w.addMapping("/*");


        try {
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }

    }

    /**
     * 创建spring上下文容器
     * @param servletContext servlet上下文对象
     * @return spring上下文容器
     */
    private WebApplicationContext getWebApplicationContext(ServletContext servletContext){
        AnnotationConfigWebApplicationContext webApp = new AnnotationConfigWebApplicationContext();
        //设置配置类
        webApp.register(MVCConfig.class);
        //设置容器的上下文
        webApp.setServletContext(servletContext);
        webApp.refresh();
        webApp.registerShutdownHook();
        return webApp;
    }


    public static void main(String[] args) {
        new MainMessage();
    }
}
